package com.qb.hotelTV.huibuTv;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import com.qb.hotelTV.R;

// 百度TV SDK相关导入
import com.baidu.duer.botsdk.BotSdk;
import com.baidu.duer.botsdk.BotIntent;
import com.baidu.duer.botsdk.BotMessageListener;

import java.util.Date;

public class MainActivity extends FragmentActivity {
    private static final String TAG = "MainActivity";
    
    // 权限请求常量
    private static final int PERMISSION_REQUEST_CODE = 1001;
    private static final String[] REQUIRED_PERMISSIONS = {
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_PHONE_STATE
    };

    /* 上一次User有动作的Time Stamp */
    private Date lastUpdateTime;
    /* 计算User有几秒没有动作的 */
    private long timePeriod;
    /* 静止超过N秒将自动进入屏保 */
    private float mHoldStillTime = 10;
    /*标识当前是否进入了屏保*/
    private boolean isAuthorized = false;
    /*时间间隔*/
    private long intervalAuthorized = 100;
    private long intervalKeypadSaver = 1000;
    private Handler mHandler01 = new Handler();
    private Handler mHandler02 = new Handler();
    PageAndListRowFragment pageAndListRowFragment;
    
    // 百度TV SDK Bot意图处理器
    private BotIntentHandler botIntentHandler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.main_browse_fragment, new PageAndListRowFragment(), "PageAndListRowFragment")
                    .commitNow();
        }
        /* 初始取得User可触碰屏幕的时间 */
        lastUpdateTime = new Date(System.currentTimeMillis());
        mHandler02.postDelayed(mTask02, intervalAuthorized);
        pageAndListRowFragment = (PageAndListRowFragment) getSupportFragmentManager().findFragmentByTag("PageAndListRowFragment");
        
        // 检查并请求权限
        checkAndRequestPermissions();
        
        // 初始化百度TV SDK语音控制
        initVoiceControl();
    }
    
    /**
     * 检查并请求权限
     */
    private void checkAndRequestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            boolean allPermissionsGranted = true;
            for (String permission : REQUIRED_PERMISSIONS) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }
            
            if (!allPermissionsGranted) {
                ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, PERMISSION_REQUEST_CODE);
            }
        }
    }
    
    /**
     * 处理权限请求结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            
            if (allGranted) {
                Toast.makeText(this, "语音权限已授权", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "需要语音权限才能使用语音控制功能", Toast.LENGTH_LONG).show();
            }
        }
    }
    
    /**
     * 初始化语音控制
     */
    private void initVoiceControl() {
        try {
            // 创建Bot意图处理器
            botIntentHandler = new BotIntentHandler(this, this);
            
            // 设置语音消息监听器
            BotSdk.getInstance().setBotMessageListener(new BotMessageListener() {
                @Override
                public void onMessage(BotIntent intent) {
                    handleVoiceCommand(intent);
                }
            });
            
            // 启动语音识别
            BotSdk.getInstance().startListening();
            
            Log.d(TAG, "语音控制初始化成功");
        } catch (Exception e) {
            Log.e(TAG, "语音控制初始化失败", e);
        }
    }
    
    /**
     * 处理语音指令
     */
    private void handleVoiceCommand(BotIntent intent) {
        if (intent == null) return;
        
        Log.d(TAG, "收到语音指令: " + intent.getName());
        
        // 使用Bot意图处理器处理语音指令
        if (botIntentHandler != null) {
            botIntentHandler.handleIntent(intent);
        }
    }
    
    /**
     * 计时线程
     */
    private Runnable mTask01 = new Runnable() {

        @Override
        public void run() {
            Date timeNow = new Date(System.currentTimeMillis());
            /* 计算User静止不动作的时间间距 */
            /**当前的系统时间 - 上次触摸屏幕的时间 = 静止不动的时间**/
            timePeriod = (long) timeNow.getTime() - (long) lastUpdateTime.getTime();
            /*将静止时间毫秒换算成秒*/
            float timePeriodSecond = ((float) timePeriod / 1000);

//            Log.d(TAG, "timePeriodSecond: " + timePeriodSecond);
//            Log.d(TAG, "isShowingHeaders: " + pageAndListRowFragment.isShowingHeaders());
            if(pageAndListRowFragment.isShowingHeaders()){
                if(timePeriodSecond > mHoldStillTime){
//                Toast.makeText(MainActivity.this, "10s未操作", Toast.LENGTH_SHORT).show();
//                模拟点击当前焦点的位置
                    pageAndListRowFragment.getView().dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER));
                    pageAndListRowFragment.getView().dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER));
//                打印pageAndListRowFragment.isShowingHeaders();
                    updateUserActionTime();
                }
            }else{
                updateUserActionTime();
            }

            /*反复调用自己进行检查*/
            mHandler01.postDelayed(mTask01, intervalKeypadSaver);
        }
    };
    /**
     * 持续屏保显示线程
     */
    private Runnable mTask02 = new Runnable() {

        @Override
        public void run() {
//
            if(isAuthorized){
                //        开始计时
                updateUserActionTime();
                mHandler01.postDelayed(mTask01, intervalKeypadSaver);
            }
            else {
//                获取pageAndListRowFragment实例
                PageAndListRowFragment pageAndListRowFragment = (PageAndListRowFragment) getSupportFragmentManager().findFragmentByTag("PageAndListRowFragment");
                if(pageAndListRowFragment != null){
                    isAuthorized = pageAndListRowFragment.isAuthorized();
                }
                /*反复调用自己进行检查*/
                mHandler02.postDelayed(mTask02, intervalAuthorized);
            }
        }
    };


    /*用户有操作的时候不断重置静止时间和上次操作的时间*/
    public void updateUserActionTime() {
        Date timeNow = new Date(System.currentTimeMillis());
        lastUpdateTime.setTime(timeNow.getTime());
    }


////    获取activity返回的结果
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if(resultCode == -1){
////            Toast.makeText(this, "返回结果", Toast.LENGTH_SHORT).show();
////            获取pageAndListRowFragment实例
//            PageAndListRowFragment pageAndListRowFragment = (PageAndListRowFragment) getSupportFragmentManager().findFragmentByTag("PageAndListRowFragment");
//            if(pageAndListRowFragment != null){
//                pageAndListRowFragment.setSelectedPosition(MyApplication.getChannelIndex(), false);
//                pageAndListRowFragment.showHeader();
//            }
//        }
//    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_UP:
                pageAndListRowFragment.toggleChannel(false);
                Log.d(TAG, "onKeyDown: 上");
                return true;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                pageAndListRowFragment.toggleChannel(true);
                Log.d(TAG, "onKeyDown: 下");
                return true;
            case KeyEvent.KEYCODE_DPAD_LEFT:
//                pageAndListRowFragment.toggleHeader();
                Log.d(TAG, "onKeyDown: 左");
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                Log.d(TAG, "onKeyDown: 右");
                break;
            case KeyEvent.KEYCODE_DPAD_CENTER:
//                pageAndListRowFragment.toggleHeader();
                Log.d(TAG, "onKeyDown: 确定");
                break;
            case KeyEvent.KEYCODE_BACK:
                this.finish();
                Log.d(TAG, "onKeyDown: 返回");
                return  true;

            case KeyEvent.KEYCODE_MENU:
                Log.d(TAG, "onKeyDown: 菜单");
                break;
        }
//        return true;
        return super.onKeyDown(keyCode, event);
    }

    @SuppressLint("RestrictedApi")
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        updateUserActionTime();
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onPause() {
        /*activity不可见的时候取消线程*/
        mHandler01.removeCallbacks(mTask01);
        mHandler02.removeCallbacks(mTask02);
        
        // 暂停语音识别
        try {
            BotSdk.getInstance().stopListening();
        } catch (Exception e) {
            Log.e(TAG, "停止语音识别失败", e);
        }
        
        super.onPause();
    }

    @Override
    protected void onResume() {
        updateUserActionTime();
        if(isAuthorized){
            /*activity显示的时候启动线程*/
            mHandler01.postAtTime(mTask01, intervalKeypadSaver);
        }else
            mHandler02.postAtTime(mTask02, intervalAuthorized);
        
        // 恢复语音识别
        try {
            BotSdk.getInstance().startListening();
        } catch (Exception e) {
            Log.e(TAG, "启动语音识别失败", e);
        }
        
        super.onResume();
    }
    
    @Override
    protected void onDestroy() {
        /*清理资源*/
        mHandler01.removeCallbacks(mTask01);
        mHandler02.removeCallbacks(mTask02);
        
        // 释放百度TV SDK资源
        try {
            BotSdk.getInstance().stopListening();
            BotSdk.getInstance().release();
        } catch (Exception e) {
            Log.e(TAG, "释放百度TV SDK资源失败", e);
        }
        
        super.onDestroy();
    }


}